import os
import tkinter as tk
from tkinter import messagebox, filedialog

from ttkbootstrap.scrolled import ScrolledFrame
from ttkbootstrap.widgets import Label, Button, Entry, Checkbutton, Notebook, Frame

from clicker_core import ClickerCore
from config_manager import ConfigManager
from ui_utils import ToolTip
from win32_utils import set_window_transparency


class AutoClickerGUI:
    def __init__(self, master):
        self.master = master
        self.master.title("还是PVP大佬")
        self.master.resizable(False, False)

        # 设置窗口透明度
        set_window_transparency(self.master)

        # 配置管理器
        self.config_manager = ConfigManager()

        # 初始化配置文件路径
        self.config_file_path = self.config_manager.config_file_path

        # ========== 配置变量初始化 ==========
        # 左键配置变量
        self.left_long_press_time = tk.DoubleVar(value=0.2)
        self.left_min_delay = tk.DoubleVar(value=0.05)
        self.left_max_delay = tk.DoubleVar(value=0.07)

        # 右键配置变量
        self.right_long_press_time = tk.DoubleVar(value=0.2)
        self.right_min_delay = tk.DoubleVar(value=0.05)
        self.right_max_delay = tk.DoubleVar(value=0.07)

        # Shift 连点配置（固定间隔）
        self.shift_hold_time = tk.DoubleVar(value=0.1)
        self.shift_interval = tk.DoubleVar(value=0.5)

        # 是否启用Shift连点
        self.enable_shift_click = tk.BooleanVar(value=False)
        
        # 鱼竿连点模式配置变量
        self.fishing_mode_enabled = tk.BooleanVar(value=False)
        self.fishing_weapon_slot = tk.IntVar(value=1)
        self.fishing_rod_slot = tk.IntVar(value=2)
        self.fishing_cast_min_delay = tk.DoubleVar(value=0.15)
        self.fishing_cast_max_delay = tk.DoubleVar(value=0.2)
        self.fishing_attack_min_count = tk.IntVar(value=10)
        self.fishing_attack_max_count = tk.IntVar(value=15)
        self.fishing_attack_min_delay = tk.DoubleVar(value=0.05)
        self.fishing_attack_max_delay = tk.DoubleVar(value=0.07)

        # 读取配置中状态标记
        self.loading_config = False
        self.has_shown_startup_prompt = False

        # 自动点击核心
        self.config_vars = {'left_long_press_time': self.left_long_press_time, 'left_min_delay': self.left_min_delay,
            'left_max_delay': self.left_max_delay, 'right_long_press_time': self.right_long_press_time,
            'right_min_delay': self.right_min_delay, 'right_max_delay': self.right_max_delay,
            'shift_hold_time': self.shift_hold_time, 'shift_interval': self.shift_interval,
            'enable_shift_click': self.enable_shift_click, 'fishing_mode_enabled': self.fishing_mode_enabled,
            'fishing_weapon_slot': self.fishing_weapon_slot, 'fishing_rod_slot': self.fishing_rod_slot,
            'fishing_cast_min_delay': self.fishing_cast_min_delay, 'fishing_cast_max_delay': self.fishing_cast_max_delay,
            'fishing_attack_min_count': self.fishing_attack_min_count, 'fishing_attack_max_count': self.fishing_attack_max_count,
            'fishing_attack_min_delay': self.fishing_attack_min_delay, 'fishing_attack_max_delay': self.fishing_attack_max_delay}
        self.clicker_core = ClickerCore(self.config_vars, self.on_fishing_mode_change)

        # ========== 界面创建 ==========
        self.create_widgets()

        # ========== 初始化时加载配置文件 ==========
        self.config_file_path = self.config_manager.load_config_file(self.config_file_path, self.config_vars)

        # 更新UI显示
        self.path_display_var.set(self.config_file_path)
        self.path_tooltip.set_text(self.config_file_path)

        # 更新频率范围显示
        self.update_frequency_ranges()
        
        # 延迟初始化模式状态显示，确保所有组件都已创建
        self.master.after(100, self.update_mode_status_display)

    def create_widgets(self):
        self.master.geometry("550x650")

        # 创建Notebook（Tab容器）
        self.notebook = Notebook(self.master, bootstyle="primary")
        self.notebook.pack(fill="both", expand=True, padx=10, pady=10)

        # 创建各个Tab页面
        self.create_left_click_tab()
        self.create_right_click_tab()
        self.create_settings_tab()

        # 添加全局控制按钮
        self.create_control_buttons()

        # 监听trace - 当配置变化时保存
        self.setup_config_traces()

    def create_left_click_tab(self):
        """创建左键连点设置Tab"""
        # 创建左键Tab
        self.left_tab = Frame(self.notebook)
        self.notebook.add(self.left_tab, text="左键连点")

        # 使用ScrolledFrame使内容可滚动
        left_scrolled = ScrolledFrame(self.left_tab, autohide=True)
        left_scrolled.pack(fill="both", expand=True)

        container = left_scrolled
        padding = {'padx': 10, 'pady': 8}
        row_idx = 0

        # 标题
        Label(container, text="【左键连点配置】", bootstyle="primary", font=("Arial", 12, "bold"), anchor='w').grid(
            row=row_idx, column=0, columnspan=2, sticky='w', pady=(10, 15))
        row_idx += 1

        # 长按时间设置
        Label(container, text="长按左键时间（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.left_long_press_time, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        # 最小延迟设置
        Label(container, text="左键最小延迟（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.left_min_delay, bootstyle="primary", width=20).grid(row=row_idx, column=1,
            sticky='w', **padding)
        row_idx += 1

        # 最大延迟设置
        Label(container, text="左键最大延迟（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.left_max_delay, bootstyle="primary", width=20).grid(row=row_idx, column=1,
            sticky='w', **padding)
        row_idx += 1

        # 频率范围显示
        Label(container, text="左键点击频率范围（次/秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        self.left_frequency_range_label = Label(container, text="", bootstyle="info", anchor='w')
        self.left_frequency_range_label.grid(row=row_idx, column=1, sticky='w', **padding)
        row_idx += 1

        # 鱼竿连点模式分割线
        Label(container, text="", bootstyle="secondary").grid(row=row_idx, column=0, columnspan=2, pady=10)
        row_idx += 1

        # 鱼竿连点模式标题
        Label(container, text="【鱼竿连点模式】", bootstyle="warning", font=("Arial", 11, "bold"), anchor='w').grid(
            row=row_idx, column=0, columnspan=2, sticky='w', **padding)
        row_idx += 1

        # 鱼竿连点模式开关 (统一的模式切换)
        self.fishing_mode_checkbtn = Checkbutton(container, text="鱼竿连点模式 (按Z键切换)",
                                                variable=self.fishing_mode_enabled, bootstyle="round-toggle")
        self.fishing_mode_checkbtn.grid(row=row_idx, column=0, columnspan=2, sticky='w', **padding)
        row_idx += 1

        # 武器位设置
        Label(container, text="武器位 (1-9):", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.fishing_weapon_slot, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        # 鱼竿位设置
        Label(container, text="鱼竿位 (1-9):", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.fishing_rod_slot, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        # 抛竿延迟设置
        Label(container, text="抛竿后最小延迟（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.fishing_cast_min_delay, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        Label(container, text="抛竿后最大延迟（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.fishing_cast_max_delay, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        # 攻击次数设置
        Label(container, text="每轮最少攻击次数:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.fishing_attack_min_count, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        Label(container, text="每轮最多攻击次数:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.fishing_attack_max_count, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        # 攻击延迟设置
        Label(container, text="攻击最小延迟（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.fishing_attack_min_delay, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        Label(container, text="攻击最大延迟（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.fishing_attack_max_delay, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        # 添加说明文字
        help_text = ("使用说明：\n"
                     "• 按住鼠标左键超过设定时间启动左键自动点击\n"
                     "• 最小/最大延迟决定点击的随机间隔范围\n"
                     "• 延迟越小，点击频率越高\n"
                     "• 鱼竿连点模式：先切换到鱼竿位右键抛竿，等待延迟后切换到武器位进行攻击\n"
                     "• 每轮攻击次数可设置随机范围，程序会在最小和最大次数间随机选择\n"
                     "• 按Z键可在普通左键连点和鱼竿连点模式间切换\n"
                     "• 鱼竿连点模式下：按Z键终止连点（右键不会终止鱼竿连点）")
        Label(container, text=help_text, bootstyle="secondary", anchor='w', justify='left', wraplength=400).grid(
            row=row_idx, column=0, columnspan=2, sticky='w', pady=(15, 5))

    def create_right_click_tab(self):
        """创建右键连点设置Tab"""
        # 创建右键Tab
        self.right_tab = Frame(self.notebook)
        self.notebook.add(self.right_tab, text="右键连点")

        # 使用ScrolledFrame使内容可滚动
        right_scrolled = ScrolledFrame(self.right_tab, autohide=True)
        right_scrolled.pack(fill="both", expand=True)

        container = right_scrolled
        padding = {'padx': 10, 'pady': 8}
        row_idx = 0

        # 标题
        Label(container, text="【右键连点配置】", bootstyle="primary", font=("Arial", 12, "bold"), anchor='w').grid(
            row=row_idx, column=0, columnspan=2, sticky='w', pady=(10, 15))
        row_idx += 1

        # 长按时间设置
        Label(container, text="右键+中键 长按时间（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.right_long_press_time, bootstyle="primary", width=20).grid(row=row_idx,
            column=1, sticky='w', **padding)
        row_idx += 1

        # 最小延迟设置
        Label(container, text="右键最小延迟（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.right_min_delay, bootstyle="primary", width=20).grid(row=row_idx, column=1,
            sticky='w', **padding)
        row_idx += 1

        # 最大延迟设置
        Label(container, text="右键最大延迟（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.right_max_delay, bootstyle="primary", width=20).grid(row=row_idx, column=1,
            sticky='w', **padding)
        row_idx += 1

        # 频率范围显示
        Label(container, text="右键点击频率范围（次/秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        self.right_frequency_range_label = Label(container, text="", bootstyle="info", anchor='w')
        self.right_frequency_range_label.grid(row=row_idx, column=1, sticky='w', **padding)
        row_idx += 1

        # Shift连点配置分割线
        Label(container, text="", bootstyle="secondary").grid(row=row_idx, column=0, columnspan=2, pady=10)
        row_idx += 1

        # Shift连点配置标题
        Label(container, text="【Shift 连点配置】", bootstyle="warning", font=("Arial", 11, "bold"), anchor='w').grid(
            row=row_idx, column=0, columnspan=2, sticky='w', **padding)
        row_idx += 1

        # Shift连点开关
        self.enable_shift_checkbtn = Checkbutton(container, text="启用 Shift+右键+中键 连点",
                                                 variable=self.enable_shift_click, bootstyle="round-toggle")
        self.enable_shift_checkbtn.grid(row=row_idx, column=0, columnspan=2, sticky='w', **padding)
        row_idx += 1

        # Shift按住时长
        Label(container, text="每次按住Shift时长（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        Entry(container, textvariable=self.shift_hold_time, bootstyle="primary", width=20).grid(row=row_idx, column=1,
            sticky='w', **padding)
        row_idx += 1

        # Shift间隔时间
        Label(container, text="Shift按下后到下次按的固定间隔（秒）:", bootstyle="primary", anchor='w').grid(row=row_idx,
            column=0, sticky='e', **padding)
        Entry(container, textvariable=self.shift_interval, bootstyle="primary", width=20).grid(row=row_idx, column=1,
            sticky='w', **padding)
        row_idx += 1

        # 添加说明文字
        help_text = ("使用说明：\n"
                     "• 按住右键+中键超过设定时间启动右键自动点击\n"
                     "• 按住Shift+右键+中键超过设定时间进入Shift模式\n"
                     "• Shift模式：按住Shift指定时间，然后等待指定间隔，循环执行")
        Label(container, text=help_text, bootstyle="secondary", anchor='w', justify='left', wraplength=400).grid(
            row=row_idx, column=0, columnspan=2, sticky='w', pady=(15, 5))

    def create_settings_tab(self):
        """创建设置Tab"""
        # 创建设置Tab
        self.settings_tab = Frame(self.notebook)
        self.notebook.add(self.settings_tab, text="设置")

        # 使用ScrolledFrame使内容可滚动
        settings_scrolled = ScrolledFrame(self.settings_tab, autohide=True)
        settings_scrolled.pack(fill="both", expand=True)

        container = settings_scrolled
        padding = {'padx': 10, 'pady': 8}
        row_idx = 0

        # 标题
        Label(container, text="【配置文件设置】", bootstyle="primary", font=("Arial", 12, "bold"), anchor='w').grid(
            row=row_idx, column=0, columnspan=2, sticky='w', pady=(10, 15))
        row_idx += 1

        # 配置文件路径
        Label(container, text="配置文件路径:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0, sticky='e',
            **padding)
        self.path_display_var = tk.StringVar()
        self.path_display_entry = Entry(container, textvariable=self.path_display_var, bootstyle="info", width=40)
        self.path_display_entry.grid(row=row_idx, column=1, sticky='w', **padding)
        self.path_tooltip = ToolTip(self.path_display_entry, text="")
        self.path_display_entry.bind("<Double-Button-1>", self.on_double_click_path)
        row_idx += 1

        # 主配置文件路径（只读）
        Label(container, text="主配置文件路径（不可修改）:", bootstyle="primary", anchor='w').grid(row=row_idx, column=0,
            sticky='e', **padding)
        self.main_settings_path_var = tk.StringVar(value=self.config_manager.main_settings_file)
        self.main_settings_entry = Entry(container, textvariable=self.main_settings_path_var, bootstyle="info",
                                         width=40, state="readonly")
        self.main_settings_entry.grid(row=row_idx, column=1, sticky='w', **padding)
        ToolTip(self.main_settings_entry, self.config_manager.main_settings_file)
        self.main_settings_entry.bind("<Double-Button-1>", self.on_double_click_main_settings)
        row_idx += 1

        # 添加说明文字
        help_text = ("配置文件说明：\n"
                     "• 双击配置文件路径可重新选择配置文件或目录\n"
                     "• 主配置文件路径不可修改，存储应用程序基本设置\n"
                     "• 配置会在修改时自动保存")
        Label(container, text=help_text, bootstyle="secondary", anchor='w', justify='left', wraplength=400).grid(
            row=row_idx, column=0, columnspan=2, sticky='w', pady=(15, 5))

    def create_control_buttons(self):
        """创建控制按钮区域"""
        # 创建底部按钮框架
        button_frame = Frame(self.master)
        button_frame.pack(fill="x", padx=10, pady=(0, 10))

        # 启动/停止监听按钮
        self.start_button = Button(button_frame, text="启动监听", bootstyle="success-outline", width=15,
                                   command=self.toggle_listening)
        self.start_button.pack(pady=10)

    def setup_config_traces(self):
        """设置配置变量监听"""
        self.left_long_press_time.trace_add('write', self.on_config_changed)
        self.left_min_delay.trace_add('write', self.on_config_changed)
        self.left_max_delay.trace_add('write', self.on_config_changed)

        self.right_long_press_time.trace_add('write', self.on_config_changed)
        self.right_min_delay.trace_add('write', self.on_config_changed)
        self.right_max_delay.trace_add('write', self.on_config_changed)

        self.shift_hold_time.trace_add('write', self.on_config_changed)
        self.shift_interval.trace_add('write', self.on_config_changed)

        # 当启用Shift连点开关变化时，也触发保存
        self.enable_shift_click.trace_add('write', self.on_config_changed)
        
        # 鱼竿连点配置监听
        self.fishing_mode_enabled.trace_add('write', self.on_fishing_enabled_changed)
        self.fishing_weapon_slot.trace_add('write', self.on_config_changed)
        self.fishing_rod_slot.trace_add('write', self.on_config_changed)
        self.fishing_cast_min_delay.trace_add('write', self.on_config_changed)
        self.fishing_cast_max_delay.trace_add('write', self.on_config_changed)
        self.fishing_attack_min_count.trace_add('write', self.on_config_changed)
        self.fishing_attack_max_count.trace_add('write', self.on_config_changed)
        self.fishing_attack_min_delay.trace_add('write', self.on_config_changed)
        self.fishing_attack_max_delay.trace_add('write', self.on_config_changed)

    def on_double_click_main_settings(self, event):
        folder = os.path.dirname(self.config_manager.main_settings_file)
        if os.path.exists(folder):
            try:
                os.startfile(folder)
            except Exception as e:
                messagebox.showwarning("无法打开目录", f"无法打开目录: {folder}\n原因: {e}")

    def on_double_click_path(self, event):
        choose_dir = messagebox.askyesno("选择路径方式", "要选择目录吗？\n如果选择 '否' 则会让你选择 .acconfig 文件。")
        old_path = self.config_file_path

        if choose_dir:
            initial_dir = os.path.dirname(old_path) if os.path.exists(
                old_path) else self.config_manager.default_config_dir
            new_dir = filedialog.askdirectory(title="选择配置文件目录", initialdir=initial_dir)
            if not new_dir:
                return
            self.config_manager.move_config_file(old_path, new_dir)
            final_path = os.path.join(new_dir, self.config_manager.default_config_filename)
            if os.path.exists(final_path):
                self.load_config_file(final_path)
        else:
            initial_dir = os.path.dirname(old_path) if os.path.exists(
                old_path) else self.config_manager.default_config_dir
            path = filedialog.askopenfilename(title="选择配置文件(.acconfig)", initialdir=initial_dir,
                                              filetypes=[("AutoClick Config", "*.acconfig"), ("All Files", "*.*")])
            if not path:
                return
            if os.path.isdir(path):
                self.config_manager.move_config_file(old_path, path)
                final_path = os.path.join(path, self.config_manager.default_config_filename)
                if os.path.exists(final_path):
                    self.load_config_file(final_path)
            else:
                if os.path.abspath(old_path) != os.path.abspath(path):
                    self.config_manager.move_config_file(old_path, path)
                if os.path.exists(path):
                    try:
                        self.load_config_file(path)
                    except ValueError as ve:
                        messagebox.showerror("错误", str(ve))
                        self.load_config_file(old_path)

    def update_frequency_ranges(self, *args):
        # 使用ClickerCore的频率计算方法
        ranges = self.clicker_core.calculate_frequency_ranges()
        self.left_frequency_range_label.config(text=ranges["left"])
        self.right_frequency_range_label.config(text=ranges["right"])

    def on_config_changed(self, *args):
        """当配置变更时：1. 更新频率范围 2. 保存配置"""
        self.update_frequency_ranges()
        if not self.loading_config:
            if hasattr(self, 'config_file_path') and self.config_file_path:
                self.config_manager.save_config_file(self.config_file_path, self.config_vars)

    def load_config_file(self, path):
        """加载配置文件"""
        self.loading_config = True
        try:
            self.config_file_path = self.config_manager.load_config_file(path, self.config_vars)
            # 更新UI显示
            self.path_display_var.set(self.config_file_path)
            self.path_tooltip.set_text(self.config_file_path)
        except Exception as e:
            messagebox.showerror("配置加载错误", str(e))
        finally:
            self.loading_config = False

    def toggle_listening(self):
        """切换监听状态"""
        if self.clicker_core.is_listening:
            self.stop_listening()
        else:
            validate_result = self.clicker_core.validate_configs()
            if isinstance(validate_result, tuple):
                messagebox.showerror("配置错误", validate_result[1])
                return
            self.start_listening()

    def start_listening(self):
        """开始监听"""
        if self.clicker_core.start_listening():
            self.start_button.config(text="停止监听", bootstyle="danger-outline")

            if not self.has_shown_startup_prompt:
                messagebox.showinfo("提示", ("1. 按住鼠标左键超过设定时间以启动左键自动点击；\n"
                                             "2. 按住右键+中键超过设定时间以启动右键自动点击；\n"
                                             "3. 按住Shift + 右键 + 中键超过设定时间则进入Shift模式（需勾选开启）；\n"
                                             "   （每次按住Shift时长 = shift_hold_time；按完后等待 shift_interval秒）\n"
                                             "4. 鱼竿连点模式：按Z键切换模式，鱼竿模式下按Z键终止连点；\n"
                                             "5. 其它鼠标键按下可取消连点，或点击 停止监听 停止；\n"
                                             "6. 双击配置路径框可重新选择配置文件或目录。"))
                self.has_shown_startup_prompt = True
        else:
            messagebox.showerror("错误", "无法启动监听器")

    def stop_listening(self):
        """停止监听"""
        if self.clicker_core.stop_listening():
            self.start_button.config(text="启动监听", bootstyle="success-outline")
        else:
            messagebox.showerror("错误", "无法停止监听器")

    def on_fishing_enabled_changed(self, *args):
        """当鱼竿连点启用状态改变时的回调"""
        if not self.loading_config:
            # 同步到核心模块的当前模式状态
            self.clicker_core.current_fishing_mode = self.fishing_mode_enabled.get()
            print(f"复选框切换: {'鱼竿连点' if self.fishing_mode_enabled.get() else '普通左键连点'} 模式")
        
        # 保存配置
        self.on_config_changed(*args)
    
    def update_mode_status_display(self):
        """更新模式状态显示 - 现在简化为只显示复选框状态"""
        try:
            # 现在模式状态完全由复选框决定
            fishing_mode = self.fishing_mode_enabled.get()
            mode_text = "鱼竿连点" if fishing_mode else "普通左键连点"
            print(f"当前模式: {mode_text}")
            
        except Exception as e:
            print(f"更新状态显示异常: {e}")

    def on_fishing_mode_change(self, fishing_mode):
        """当鱼竿模式状态改变时的回调函数"""
        print(f"Z键切换模式: {'鱼竿连点' if fishing_mode else '普通左键连点'}")
        # 使用after方法确保在主线程中更新UI
        self.master.after(0, lambda: self.sync_mode_state(fishing_mode))
    
    def sync_mode_state(self, fishing_mode):
        """同步模式状态到UI"""
        try:
            # 设置loading_config标志防止递归回调
            self.loading_config = True
            
            # 同步复选框状态
            self.fishing_mode_enabled.set(fishing_mode)
            
            mode_text = "鱼竿连点" if fishing_mode else "普通左键连点"
            print(f"同步UI状态: {mode_text}")
            
        except Exception as e:
            print(f"同步状态异常: {e}")
        finally:
            self.loading_config = False

    def on_close(self):
        """窗口关闭事件"""
        try:
            self.clicker_core.stop_listening()
        except Exception as e:
            print(f"关闭时异常: {e}")
        self.master.destroy()
